
#include "Connection.h"

Connection::Connection(EventLoop *loop, Socket *clientsock)
    : loop_(loop), clientsock_(clientsock)
{
    clientchannel_ = new Channel(loop_, clientsock->fd());
    clientchannel_->setreadcallback(std::bind(&Channel::onmessage, clientchannel_));
    clientchannel_->setclosecallback(std::bind(&Connection::closecallback,this));
    clientchannel_->seterrorcallback(std::bind(&Connection::errorcallback,this));
    clientchannel_->enablereading();
    clientchannel_->useet();

    // printf(" hahaNew client connected: %s:%d\n", clientsock_->ip().c_str(), clientsock_->port());
}
Connection::~Connection()
{
    delete clientsock_;
    delete clientchannel_;
}
std::string Connection::ip()
{
    return clientsock_->ip();
}
uint16_t Connection::port()
{
    return clientsock_->port();
}

int Connection::fd() const
{
    return clientsock_->fd();
}

void Connection::closecallback()
{
    // printf("client(eventfd=%d) disconnected.\n", fd());
    // close(fd());
    closecallback_(this);
}
void Connection::errorcallback()
{
    // printf("else error\n");
    // close(fd());
    errorcallback_(this);
}

void Connection::setclosecallback(std::function<void(Connection*)> f)
{
    closecallback_ = f;
}
void Connection::seterrorcallback(std::function<void(Connection*)> f)
{
    errorcallback_ = f;
}